﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using HRM.Controller;

namespace HRM.Common
{
    public partial class QT_TruocDay : UserControl
    {
        PremiumClient _wcfPremium;
        EmployeeClient _wcfEmployee;
        private bool IsLoading = true;
        public delegate void SuaThongTinQuaTrinh(int Premium_Id, int Employee_Id);
        public event SuaThongTinQuaTrinh suaThongTinQuaTrinh;

        public DataGridViewRow SelectedRow
        {
            get
            {
                if (dgvPremium.SelectedCells.Count > 0)
                    return dgvPremium.SelectedCells[0].OwningRow;
                else
                    return null;
            }
        }

        public QT_TruocDay()
        {
            InitializeComponent();
            //
            _wcfEmployee = Service.Employee();
            _wcfPremium = Service.Premium();
            //
            dgvPremium.AutoGenerateColumns = false;
            AddColumnPremium();
        }

        /*public method*/

        /// <summary>
        /// Hiển thị quá trình trước đây đã nhập của số sổ BHXH
        /// </summary>
        /// <param name="soSoBHXH"></param>
        public void QuaTrinhTruocDay(string soSoBHXH)
        {
            LoadPremium(soSoBHXH);
        }

        /// <summary>
        /// Lấy danh sách quá trình trước đây được nhập mới trong ngày
        /// </summary>
        public void DSNhapMoi()
        {
            LoadByDay(DateTime.Today);
        }

        /// <summary>
        /// Gán Premium_Id được selected
        /// </summary>
        /// <param name="Premium_Id"></param>
        //public void SelectedRow(int Premium_Id)
        //{
        //    //foreach (DataGridViewRow dgv in dgvPremium.Rows)
        //    //{
        //    //    if ( Globals.Object_GetValue<int>(dgv.Cells["Premium_ID"].Value) == Premium_Id)
        //    //    {
        //    //        dgvPremium.CurrentCell = dgv.Cells["Premium_SIBookNo"];
        //    //        dgv.Cells["Premium_SIBookNo"].Selected = true;
        //    //        dgv.Selected = true;
        //    //        break;
        //    //    }
        //    //}
        //}

        private void AddColumnPremium()
        {
            dgvPremium.Columns.Clear();
            //
            UISetting.AddColumn(ref dgvPremium, "Premium_Date", "Ngày nhập", "C", 100, false, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_EmployeeID", "EmployeeId", "", 1, false, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_SIBookNo", "Số sổ", "C", 80, true, true);

            UISetting.AddColumn(ref dgvPremium, "Premium_FromDate", "Từ tháng", "C", 80, true, true).DefaultCellStyle.Format="MM/yyyy";

            UISetting.AddColumn(ref dgvPremium, "Premium_ToDate", "Đến tháng", "C", 90, true, true).DefaultCellStyle.Format = "MM/yyyy"; ;

            UISetting.AddColumn(ref dgvPremium, "Premium_WorkUnit", UpdateUI.GetString("donvilamviec"), "", 150, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_Job", UpdateUI.GetString("nghenghiep"), "", 100, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_Salary", "ML", "R", 70, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_BasicFactor", "HSL", "R", 60, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_PositionFactor", "HS Cvụ", "R", 90, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_SeniorityFactorPercent", "% TNNghề", "R", 60, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_SeniorityFactor", "HS TNNghề", "R", 60, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_OverSeniorityFactorPercent", "% TNVK", "R", 60, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_OverSeniorityFactor", "HS TNVK", "R", 60, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_AreaFactor", "HS KV", "R", 100, false, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_MonthNo", "Số tháng", "R", 100, true, true);
            UISetting.AddColumn(ref dgvPremium, "PA", "PA", "R", 60, true, true);
            UISetting.AddColumn(ref dgvPremium, "Premium_Description", UpdateUI.GetString("ghichu"), "", 100, false, true);
            UISetting.AddColumn(ref dgvPremium, "Detail_ID", "Detail_ID", "", 30, false, true);
        }

        /// <summary>
        /// Lấy danh sách quá trình trước đây theo số sổ BHXH
        /// </summary>
        /// <param name="_SIBookNo"></param>
        private void LoadPremium(string _SIBookNo)
        {
            try
            {
                IsLoading = true;
                DataTable dt = new DataTable();
                PremiumClient _wcfPremium = Service.Premium();
                //dt = _wcfPremium.Premium_QTBH(Program.strBranchCode, _SIBookNo, 0, DateTime.MinValue, DateTime.MaxValue).Tables[0];
                dt = _wcfPremium.Premium_GetBySIBookNo(_SIBookNo, false).Tables[0];
                dgvPremium.Rows.Clear();
                dt.DefaultView.Sort = "Premium_FromDate ASC";
                dt = dt.DefaultView.ToTable();
                if (dt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dgvPremium.Rows.Insert(i, 1);
                        dgvPremium.Rows[i].Cells["Premium_SIBookNo"].Value = dt.Rows[i]["Premium_SIBookNo"];

                        //dgvList.Columns["Premium_ToDate"].Frozen = true;
                        if (Convert.ToDateTime(dt.Rows[i]["Premium_Date"]).ToString("dd/MM/yyyy") != "01/01/2000")
                            dgvPremium.Rows[i].Cells["Premium_Date"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_Date"]).ToString("dd/MM/yyyy");
                        dgvPremium.Rows[i].Cells["Premium_ID"].Value = dt.Rows[i]["Premium_ID"].ToString();
                        dgvPremium.Rows[i].Cells["Premium_EmployeeID"].Value = dt.Rows[i]["Premium_EmployeeID"].ToString();
                        //dgvPremium.Rows[i].Cells["RowNumber"].Value = dt.Rows[i]["RowNumber"].ToString();
                        dgvPremium.Rows[i].Cells["Premium_FromDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_FromDate"]);//.ToString("MM/yyyy");
                        //--dgvPremium.Rows[i].Cells["Premium_ToDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_ToDate"]).ToString("MM/yyyy");
                        dgvPremium.Rows[i].Cells["Premium_ToDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_ToDate"]);//.ToString("MM/yyyy");
                        dgvPremium.Rows[i].Cells["Premium_WorkUnit"].Value = dt.Rows[i]["Premium_WorkUnit"].ToString();
                        dgvPremium.Rows[i].Cells["Premium_Job"].Value = dt.Rows[i]["Premium_Job"].ToString();
                        dgvPremium.Rows[i].Cells["Premium_Salary"].Value = dt.Rows[i]["Premium_Salary"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_Salary"]).ToString("#,##0");
                        dgvPremium.Rows[i].Cells["Premium_BasicFactor"].Value = dt.Rows[i]["Premium_BasicFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_BasicFactor"]).ToString("#0.0##");
                        dgvPremium.Rows[i].Cells["Premium_PositionFactor"].Value = dt.Rows[i]["Premium_PositionFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_PositionFactor"]).ToString("#0.0##");
                        dgvPremium.Rows[i].Cells["Premium_SeniorityFactor"].Value = dt.Rows[i]["Premium_SeniorityFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_SeniorityFactor"]).ToString("#0.0##");

                        dgvPremium.Rows[i].Cells["Premium_OverSeniorityFactor"].Value = dt.Rows[i]["Premium_OverSeniorityFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_OverSeniorityFactor"]).ToString("#0.0##");
                        dgvPremium.Rows[i].Cells["Premium_AreaFactor"].Value = dt.Rows[i]["Premium_AreaFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_AreaFactor"]).ToString("#0.0##");
                        dgvPremium.Rows[i].Cells["Premium_MonthNo"].Value = dt.Rows[i]["Premium_MonthNo"].ToString();

                        string PA = dt.Rows[i]["Detail_InsTypeCode"].ToString();
                        PA = "ON,TS,OF".IndexOf(PA) > 0 ? PA : "";
                        dgvPremium.Rows[i].Cells["PA"].Value = PA;

                        dgvPremium.Rows[i].Cells["Premium_Description"].Value = dt.Rows[i]["Premium_Description"].ToString();
                        dgvPremium.Rows[i].Cells["Detail_ID"].Value = dt.Rows[i]["Detail_ID"].ToString();

                        //Tính % nghề, vk

                        decimal BasicFactor = UISetting.GetDecimalNo(dgvPremium.Rows[i].Cells["Premium_BasicFactor"].Value.ToString());
                        decimal PosionFactor = UISetting.GetDecimalNo(dgvPremium.Rows[i].Cells["Premium_PositionFactor"].Value.ToString());
                        decimal OverFactor = UISetting.GetDecimalNo(dgvPremium.Rows[i].Cells["Premium_OverSeniorityFactor"].Value.ToString());
                        decimal JobFactor = UISetting.GetDecimalNo(dgvPremium.Rows[i].Cells["Premium_SeniorityFactor"].Value.ToString());
                        //
                        if (OverFactor != 0)
                        {
                            decimal OverFactor_Percent = (OverFactor * 100 / BasicFactor);
                            dgvPremium.Rows[i].Cells["Premium_OverSeniorityFactorPercent"].Value = Math.Round(OverFactor_Percent).ToString();
                        }
                        if (JobFactor != 0)
                        {
                            decimal JobFactor_Percnet = (JobFactor * 100 / (BasicFactor + PosionFactor + OverFactor));
                            dgvPremium.Rows[i].Cells["Premium_SeniorityFactorPercent"].Value = Math.Round(JobFactor_Percnet).ToString();
                        }
                    }

                    //duyệt lại tìm dòng không tham gia, đảm bảo đã order theo từ tháng
                    int counter = 0;
                    DateTime FromDate, ToDate, NextFromDate;
                    for(int i = 1; i < dt.Rows.Count; i++)
                    {
                        ToDate = (DateTime)dt.Rows[i - 1]["Premium_ToDate"];
                        FromDate = (DateTime)dt.Rows[i]["Premium_FromDate"];
                        
                        //if(
                        //NextFromDate = (DateTime)dgvPremium.Rows[i+1].Cells["Premium_FromDate"].Value;
                        //
                        if (ToDate.AddMonths(1) != FromDate && Globals.DB_GetString(dt.Rows[i]["Premium_Type"]) != "CT")
                        {
                            //ko tham gia
                            dgvPremium.Rows.Insert(i + counter, 1);
                            dgvPremium.Rows[i + counter].Cells["Premium_FromDate"].Value = ToDate.AddMonths(1);
                            dgvPremium.Rows[i + counter].Cells["Premium_ToDate"].Value = FromDate.AddMonths(-1);
                            dgvPremium.Rows[i + counter].Cells["Premium_WorkUnit"].Value = "Không tham gia";
                            //
                            dgvPremium.Rows[i + counter].DefaultCellStyle.BackColor = Color.Yellow;
                            dgvPremium.Rows[i + counter].ReadOnly = true;
                            counter += 1;
                        }
                    }
                }
                //
                IsLoading = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
            }
        }

        /// <summary>
        /// Lấy danh sách những bản ghi nhập thêm mới trong ngày
        /// </summary>
        private void LoadByDay(DateTime inputDate)
        {
            DataTable dt = Premium_Controller.Instance().Premium_GetInputByDate(inputDate);
            dgvPremium.DataSource = dt;
        }


        private void dgvPremium_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int premium_id = dgvPremium.Rows[e.RowIndex].GetValue<int>("Premium_ID");
            int employee_id = dgvPremium.Rows[e.RowIndex].GetValue<int>("Premium_EmployeeID");
            if (premium_id > 0 && suaThongTinQuaTrinh != null)
                suaThongTinQuaTrinh(premium_id,employee_id);
        }

        private void dgvPremium_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void dgvPremium_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (!IsLoading)
            {
                int premium_id = dgvPremium.Rows[e.RowIndex].GetValue<int>("Premium_ID");
                int employee_id = dgvPremium.Rows[e.RowIndex].GetValue<int>("Premium_EmployeeID");
                if (premium_id > 0 && suaThongTinQuaTrinh != null)
                    suaThongTinQuaTrinh(premium_id, employee_id);
            }
        }
    }
}
